from __future__ import print_function

from keras.layers.recurrent import LSTM
from keras.models import Sequential, Graph
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D, AveragePooling2D
from keras.layers.core import Activation, Dense, Flatten, Dropout, Reshape, Merge
from keras.layers.advanced_activations import LeakyReLU
from keras.layers.normalization import BatchNormalization
from keras.regularizers import l2
from keras import backend as K

from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.optimizers import SGD
from keras.utils import np_utils

def get_model():
    filters=64
    conv = Graph()
    conv.add_input(name='conv_input', input_shape=(3, 32, 32))
    i=0
    conv.add_node(Convolution2D(filters, 7, 7, border_mode='same'), name='conv_'+str(2*i), input='conv_input')
    conv.add_node(Activation('relu'), name='conv_activation_'+str(2*i), input='conv_'+str(2*i))
    conv.add_node(MaxPooling2D(pool_size=(3, 3)), name='max_pooling', input='conv_activation_'+str(2*i))
    i=1
    conv.add_node(Convolution2D(filters, 1, 1, border_mode='same', subsample=(2,2)), name='conv_'+str(3*i), input='max_pooling')
    conv.add_node(Activation('relu'), name='conv_activation_'+str(3*i), input='conv_'+str(3*i))
    conv.add_node(Convolution2D(filters, 3, 3, border_mode='same'), name='conv_'+str(3*i+1), input='conv_'+str(3*i))
    conv.add_node(Activation('relu'), name='conv_activation_'+str(3*i+1), input='conv_'+str(3*i+1))
    conv.add_node(Convolution2D(filters*4, 1, 1, border_mode='same'), name='conv_'+str(3*i+2), input='conv_activation_'+str(3*i+1))
    conv.add_node(Activation('relu'), name='merge_conv_'+str(i), input='conv_'+str(3*i+2))
    conv.add_node(BatchNormalization(), name='batch_norm_'+str(i), input='merge_conv_'+str(i))
    for i in range(2, 10):
        print(3*i)
        print(3*i+1)
        if i!=0 and i%3==0:
            filters=filters*2
        conv.add_node(Convolution2D(filters, 1, 1, border_mode='same', subsample=(2,2)), name='conv_'+str(3*i), input='batch_norm_'+str(i-1))
        conv.add_node(Activation('relu'), name='conv_activation_'+str(3*i), input='conv_'+str(3*i))
        conv.add_node(Convolution2D(filters, 3, 3, border_mode='same'), name='conv_'+str(3*i+1), input='conv_activation_'+str(3*i))
        conv.add_node(Activation('relu'), name='conv_activation_'+str(3*i+1), input='conv_'+str(3*i+1))
        conv.add_node(Convolution2D(filters*4, 1, 1, border_mode='same'), name='conv_'+str(3*i+2), input='conv_activation_'+str(3*i+1))
        conv.add_node(Activation('relu'), name='merge_conv_'+str(i), inputs=['conv_'+str(3*i+2), 'merge_conv_'+str(i-1)])
        conv.add_node(BatchNormalization(), name='batch_norm_'+str(i), input='merge_conv_'+str(i))

    conv.add_node(AveragePooling2D(pool_size=(8, 8)), name='average_pooling', input='batch_norm_'+str(9))
    conv.add_node(Flatten(), name='flatten', input='average_pooling')
    conv.add_node((Dense(10, activation='softmax')), name='out_activation', input='flatten')
    conv.add_output(name='output', input='out_activation')
    print(conv.summary())
    return conv

'''Train a simple deep CNN on the CIFAR10 small images DataUtils.
GPU run command:
    THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python cifar10_cnn.py
It gets down to 0.65 test logloss in 25 epochs, and down to 0.55 after 50 epochs.
(it's still underfitting at that point, though).
Note: the data was pickled with Python 2, and some encoding issues might prevent you
from loading it in Python 3. You might have to load it in Python 2,
save it in a different format, load it in Python 3 and repickle it.
'''



batch_size = 32
nb_classes = 10
nb_epoch = 200
data_augmentation = False

# input image dimensions
img_rows, img_cols = 32, 32
# the CIFAR10 images are RGB
img_channels = 3

# the data, shuffled and split between train and test sets
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)

model = get_model()

# let's train the model using SGD + momentum (how original).
sgd = SGD(lr=0.01, momentum=0.9, nesterov=True)
for output_name in model.output_order:
    print(output_name)

model.compile(loss={'output':'categorical_crossentropy'}, optimizer=sgd)

X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255

if not data_augmentation:
    print('Not using data augmentation.')
    model.fit({'conv_input':X_train, 'output':Y_train}, batch_size=batch_size,
              nb_epoch=nb_epoch,
              validation_data=({'conv_input':X_test, 'output':Y_test}), shuffle=True)

else:
    print('Using real-time data augmentation.')

    # this will do preprocessing and realtime data augmentation
    datagen = ImageDataGenerator(
        featurewise_center=False,  # set input mean to 0 over the DataUtils
        samplewise_center=False,  # set each sample mean to 0
        featurewise_std_normalization=False,  # divide inputs by std of the DataUtils
        samplewise_std_normalization=False,  # divide each input by its std
        zca_whitening=False,  # apply ZCA whitening
        rotation_range=0,  # randomly rotate images in the range (degrees, 0 to 180)
        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)
        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)
        horizontal_flip=True,  # randomly flip images
        vertical_flip=False)  # randomly flip images

    # compute quantities required for featurewise normalization
    # (std, mean, and principal components if ZCA whitening is applied)
    datagen.fit(X_train)

    # fit the model on the batches generated by datagen.flow()
    model.fit_generator(datagen.flow(X={'conv_input':X_train},y={'output':Y_train}, batch_size=batch_size),
                        samples_per_epoch=X_train.shape[0],
                        nb_epoch=nb_epoch,
                        validation_data=({'conv_input':X_test, 'output':Y_test}),
                        nb_worker=1)